//
//  ASSession+Coding.m
//  AppleSession
//
//  Created by 吴双 on 2023/1/29.
//

#import "ASSession+Coding.h"
#import <AltSign/AltSign.h>
#import "ASSession+Private.h"

#define ALTDecode(cls, sel) [coder decodeObjectOfClass:[cls class] forKey:NSStringFromSelector(@selector(sel))]
#define ALTEncode(property) [coder encodeObject:self.property forKey:NSStringFromSelector(@selector(property))]

@implementation ALTAccount (Coding)

+ (BOOL)supportsSecureCoding {
    return YES;
}

- (void)encodeWithCoder:(nonnull NSCoder *)coder {
    ALTEncode(appleID); ALTEncode(identifier); ALTEncode(firstName); ALTEncode(lastName);
}

- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder {
    NSString *appleID = ALTDecode(NSString, appleID);
    NSString *identifier = ALTDecode(NSString, identifier);
    NSString *firstName = ALTDecode(NSString, firstName);
    NSString *lastName = ALTDecode(NSString, lastName);
    if (appleID && identifier && firstName && lastName) {
        self = [super init];
        if (self) {
            self.appleID = appleID;
            self.identifier = identifier;
            self.firstName = firstName;
            self.lastName = lastName;
        }
        return self;
    }
    return nil;
}

@end



@implementation ALTAppleAPISession (Coding)

+ (BOOL)supportsSecureCoding {
    return YES;
}

- (void)encodeWithCoder:(nonnull NSCoder *)coder {
    ALTEncode(dsid); ALTEncode(authToken); ALTEncode(anisetteData);
}

- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder {
    NSString *dsid = ALTDecode(NSString, dsid);
    NSString *authToken = ALTDecode(NSString, authToken);
    ALTAnisetteData *anisetteData = ALTDecode(ALTAnisetteData, anisetteData);
    if (dsid && authToken && anisetteData) {
        return [self initWithDSID:dsid authToken:authToken anisetteData:anisetteData];
    }
    return nil;
}

@end


@implementation ASAccountSession (Coding)

+ (BOOL)supportsSecureCoding {
    return YES;
}

- (void)encodeWithCoder:(nonnull NSCoder *)coder {
    ALTEncode(account); ALTEncode(session);
}

- (nullable instancetype)initWithCoder:(nonnull NSCoder *)coder {
    ALTAccount *account = ALTDecode(ALTAccount, account);
    ALTAppleAPISession *session = ALTDecode(ALTAppleAPISession, session);
    if (account && session) {
        return [self initWithSession:session account:account];
    }
    return nil;
}

@end
